package com.gears_software.sxdc.dccx.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.utils.overlay.SmoothMoveMarker;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.amap.api.trace.LBSTraceClient;
import com.amap.api.trace.TraceListener;
import com.amap.api.trace.TraceLocation;
import com.amap.api.trace.TraceOverlay;
import com.bigkoo.pickerview.OptionsPickerView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.db.DBUtils;
import com.gears_software.sxdc.dccx.data.finder.IBankFinder;
import com.gears_software.sxdc.dccx.data.finder.IBaseFinder;
import com.gears_software.sxdc.dccx.data.finder.IVehicleFinder;
import com.gears_software.sxdc.dccx.data.finder.IVouchersFinder;
import com.gears_software.sxdc.dccx.data.finder.IZPOrderFinder;
import com.gears_software.sxdc.dccx.data.finder.RequestUrl;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.AboutModel;
import com.gears_software.sxdc.dccx.data.model.CanUseVouchersModel;
import com.gears_software.sxdc.dccx.data.model.DriverPositionModel;
import com.gears_software.sxdc.dccx.data.model.LatLonListModel;
import com.gears_software.sxdc.dccx.data.model.LatLonModel;
import com.gears_software.sxdc.dccx.data.model.LocLocationModel;
import com.gears_software.sxdc.dccx.data.model.MsgModel;
import com.gears_software.sxdc.dccx.data.model.PositionEntity;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.UserBalance;
import com.gears_software.sxdc.dccx.data.model.ValuationRuleModel;
import com.gears_software.sxdc.dccx.data.model.VouchersModel;
import com.gears_software.sxdc.dccx.data.model.ZPOrderModel;
import com.gears_software.sxdc.dccx.data.model.request.RBalanceTrading;
import com.gears_software.sxdc.dccx.data.model.request.RCancelZPOrderModel;
import com.gears_software.sxdc.dccx.data.model.request.RChargeModel;
import com.gears_software.sxdc.dccx.data.model.request.RZCOrderRatedModel;
import com.gears_software.sxdc.dccx.data.sharedPreference.DCCXSp_;
import com.gears_software.sxdc.dccx.ui.map.LocationTask;
import com.gears_software.sxdc.dccx.ui.map.OnLocationGetListener;
import com.gears_software.sxdc.dccx.ui.map.RegeocodeTask;
import com.gears_software.sxdc.dccx.ui.map.overlay.DrivingRouteOverlay;
import com.gears_software.sxdc.dccx.ui.map.recordutil.Util;
import com.gears_software.sxdc.dccx.ui.util.MaterialDialogProgress;
import com.gears_software.sxdc.dccx.ui.util.YuYin;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.orhanobut.logger.Logger;
import com.pingplusplus.android.Pingpp;
import com.sdsmdg.tastytoast.TastyToast;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.androidannotations.rest.spring.annotations.RestService;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Stack;

import qiu.niorgai.StatusBarCompat;


/**
 * Created by chezhenzhen on 2017/9/26.
 */

@EActivity
public class WaitForJieJiaNewActivity extends AppCompatActivity implements AMap.OnMapLoadedListener, LocationSource, OnLocationGetListener, RouteSearch.OnRouteSearchListener, TraceListener {
    @App
    DCCXApplication app;
    MapView mMapView;
    //地图对象
    AMap aMap;
    TextView right_icon;
    TextView back_icon;
    TextView actionbar_title;
    TextView txt_cancel_order;
    TextView txt_wait_count;
    TextView txt_wait;
    SimpleDraweeView img_avatar;
    TextView txt_drivername;
    TextView txt_vehicleno;
    TextView txt_vehiclecolor;
    TextView txt_carmodel;
    TextView txt_tel;
    TextView tv_zhifubao_icon;
    TextView tv_weixin_icon;
    TextView tv_yu_e_icon;
    TextView txt_money;
    TextView txt_wait_show;
    TextView txt_youhui;
    TextView txt_right_icon;
    TextView txt_distance;
    TextView txt_time;
    TextView txt_amount;
    RelativeLayout re_youhui;
    RelativeLayout re_cancel_trip;
    RelativeLayout re_hotline;
    RelativeLayout re_wait;
    LinearLayout ly_trip;
    LinearLayout ly_zhifu;
    LinearLayout ly_pingjia;
    LinearLayout ly_wait;
    LinearLayout ly_yugu;
    RadioButton rb_zhifubao;
    RadioButton rb_weixin;
    RadioButton rb_yu_e;
    RadioGroup rg_zhifu;
    Button btn_pay;
    View line1;
    View line2;
    RatingBar ratingBar;
    Button btn_cancel;
    Button btn_confrim;
    @Extra
    LatLng mStartPosition; //起点
    @Extra
    LatLng mEndPosition; //终点
    @Extra
    ZPOrderModel orderModelDetail;
    @Bean
    DBUtils dbUtils;
    @RestService
    IZPOrderFinder izpOrderFinder;
    @Bean
    GearsErrorHandler errorHandler;
    @RestService
    IBaseFinder baseFinder;
    @RestService
    IVouchersFinder vouchersFinder;
    @Pref
    DCCXSp_ sp;
    LatLng mDriverPosition; //司机位置
    private LocationTask mLocationTask;
    private RegeocodeTask mRegeocodeTask;
    private OnLocationChangedListener mListener = null;//定位监听器
    private Marker mEndLocationMark;//终点marker
    private Marker mStartLocationMark;//起点marker
    private Marker mCarLocationMark;//起点marker

    private static ArrayList<Marker> markers = new ArrayList<Marker>();
    TimeCode timeCode;
    Context context;
    private RouteSearch mRouteSearch;
    private DriveRouteResult mDriveRouteResult;
    int flag = 1;
    DrivingRouteOverlay drivingRouteOverlay;
    int span;
    List<LatLng> latLngs = new ArrayList<LatLng>();
    SmoothMoveMarker smoothMarker;
    int duration;
    boolean mIsFirst = true;
    private PolylineOptions mPolyoptions, tracePolytion;
    private Polyline mpolyline;
    private List<TraceLocation> mTracelocationlist = new ArrayList<TraceLocation>();
    List<TraceLocation> locationList = new ArrayList<TraceLocation>();

    private List<TraceOverlay> mOverlayList = new ArrayList<TraceOverlay>();
    private List<AMapLocation> recordList = new ArrayList<AMapLocation>();
    private int tracesize = 8;
    private int mDistance = 0;
    private TraceOverlay mTraceoverlay;
    private Marker mlocMarker;
    MyLocationStyle myLocationStyle;
    ZPOrderModel zpOrderModel;
    MaterialDialogProgress progress;
    ValuationRuleModel ruleModel;//计价规则实体类
    int putshType = 0;//推送type状态
    String hotline = "";
    int chanel = 1;
    RChargeModel chargeModel = new RChargeModel();
    RBalanceTrading balanceTrading = new RBalanceTrading();
    @RestService
    IBankFinder bankFinder;
    String clinetIp = "";
    int RESULT_CODE = 0;
    String lat = "";
    String lon = "";
    // 语音合成对象
    private SpeechSynthesizer mTts;
    OptionsPickerView pickerView;
    List<CanUseVouchersModel> vouchersModelList = new ArrayList<CanUseVouchersModel>();
    DriverPositionModel driverPositionModel;
    String voucherid = "";
    List<LatLng> driverLatLonList = new ArrayList<LatLng>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_waitforjiejia);
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));

        context = this;
        progress = new MaterialDialogProgress(this);
        actionbar_title = (TextView) findViewById(R.id.actionbar_title);
        back_icon = (TextView) findViewById(R.id.back_icon);
        right_icon = (TextView) findViewById(R.id.right_icon);
        img_avatar = (SimpleDraweeView) findViewById(R.id.img_avatar);
        txt_cancel_order = (TextView) findViewById(R.id.txt_cancel_order);
        txt_wait_count = (TextView) findViewById(R.id.txt_wait_count);
        txt_tel = (TextView) findViewById(R.id.txt_tel);
        txt_drivername = (TextView) findViewById(R.id.txt_drivername);
        txt_vehiclecolor = (TextView) findViewById(R.id.txt_vehiclecolor);
        txt_vehicleno = (TextView) findViewById(R.id.txt_vehicleno);
        txt_carmodel = (TextView) findViewById(R.id.txt_carmodel);
        txt_wait = (TextView) findViewById(R.id.txt_wait);
        txt_money = (TextView) findViewById(R.id.txt_money);
        txt_youhui = (TextView) findViewById(R.id.txt_youhui);
        txt_distance = (TextView) findViewById(R.id.txt_distance);
        txt_time = (TextView) findViewById(R.id.txt_time);
        txt_amount = (TextView) findViewById(R.id.txt_amount);
        re_youhui = (RelativeLayout) findViewById(R.id.re_youhui);
        tv_zhifubao_icon = (TextView) findViewById(R.id.tv_zhifubao_icon);
        tv_weixin_icon = (TextView) findViewById(R.id.tv_weixin_icon);
        tv_yu_e_icon = (TextView) findViewById(R.id.tv_yu_e_icon);
        txt_right_icon = (TextView) findViewById(R.id.txt_right_icon);
        re_wait = (RelativeLayout) findViewById(R.id.re_wait);
        ly_trip = (LinearLayout) findViewById(R.id.ly_trip);
        ly_zhifu = (LinearLayout) findViewById(R.id.ly_zhifu);
        ly_wait = (LinearLayout) findViewById(R.id.ly_wait);
        ly_yugu = (LinearLayout) findViewById(R.id.ly_yugu);
        txt_wait_show = (TextView) findViewById(R.id.txt_wait_show);
        re_cancel_trip = (RelativeLayout) findViewById(R.id.re_cancel_trip);
        re_hotline = (RelativeLayout) findViewById(R.id.re_hotline);
        rg_zhifu = (RadioGroup) findViewById(R.id.rg_zhifu);
        rb_zhifubao = (RadioButton) findViewById(R.id.rb_zhifubao);
        rb_weixin = (RadioButton) findViewById(R.id.rb_weixin);
        rb_yu_e = (RadioButton) findViewById(R.id.rb_yu_e);
        line1 = findViewById(R.id.line1);
        line2 = findViewById(R.id.line2);
        btn_pay = (Button) findViewById(R.id.btn_pay);
        ly_pingjia = (LinearLayout) findViewById(R.id.ly_pingjia);
        ratingBar = (RatingBar) findViewById(R.id.ratingBar);
        btn_cancel = (Button) findViewById(R.id.btn_cancel);
        btn_confrim = (Button) findViewById(R.id.btn_confirm);

        mMapView = (MapView) findViewById(R.id.mMapView);
        mMapView.onCreate(savedInstanceState);
        izpOrderFinder.setRestErrorHandler(errorHandler);
        bankFinder.setRestErrorHandler(errorHandler);
        baseFinder.setRestErrorHandler(errorHandler);
        vouchersFinder.setRestErrorHandler(errorHandler);
        actionbar_title.setText("等待接驾");

        mLocationTask = new LocationTask(this);
        mRegeocodeTask = new RegeocodeTask(this);

        myLocationStyle = new MyLocationStyle();

        //路径规划
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);

        timeCode = new TimeCode(120000, 1000);
        timeCode.start();

        initIconFont();
        initMap();
        createBindData();
        aMap.setOnMapLoadedListener(this);
        zoomToSpan(200);
        initpolyline();
        GetNetIp();

    }

    void initIconFont() {
        back_icon.setTypeface(app.iconfont);
        back_icon.setText(R.string.back_icon);
        right_icon.setTypeface(app.iconfont);
        txt_tel.setTypeface(app.iconfont);
        right_icon.setVisibility(View.GONE);
        tv_zhifubao_icon.setTypeface(app.iconfont);
        tv_weixin_icon.setTypeface(app.iconfont);
        tv_yu_e_icon.setTypeface(app.iconfont);
        txt_right_icon.setTypeface(app.iconfont);
    }

    private void initMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        smoothMarker = new SmoothMoveMarker(aMap);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
        //设置显示定位按钮 并且可以点击
        UiSettings settings = aMap.getUiSettings();
        //地图上不显示放大缩小按钮
        settings.setZoomControlsEnabled(false);
        mTraceoverlay = new TraceOverlay(aMap);


    }

    String driverLon = "";
    String driverLat = "";

    //Activity第一次进入或者退出后再进来时，执行此方法
    private void createBindData() {
        if (getIntent().getExtras().get("msgModel") != null || getIntent().getExtras().get("extraStr") != null) {
            MsgModel msg = (MsgModel) getIntent().getExtras().get("msgModel");

            if (!getIntent().getExtras().get("extraStr").equals("")) {
                String[] strs = getIntent().getExtras().getString("extraStr").split(",");
                driverLon = strs[0];
                driverLat = strs[1];
            }
            zpOrderModel = msg.getFdata();
            putshType = msg.getType();
            orderState(putshType, msg.getMessage());
        } else {
            zpOrderModel = orderModelDetail;
            putshType = Integer.valueOf(zpOrderModel.getOrderstatus());
            if (putshType != 1) {
                orderState(putshType, "");
            }
        }
    }

    private void orderState(int putshType, String message) {
        switch (putshType) {
            case 1:
                TastyToast.makeText(this, message, app.LONG, app.WARNING);
                timeCode.onFinish();
                if (mStartPosition == null) {
                    mStartPosition = new LatLng(Double.valueOf(zpOrderModel.getDeplatitude().toString()), Double.valueOf(zpOrderModel.getDeplongitude().toString()));
                }
                if (mEndPosition == null) {
                    mEndPosition = new LatLng(Double.valueOf(zpOrderModel.getDestlatitude().toString()), Double.valueOf(zpOrderModel.getDestlongitude().toString()));
                }
                txt_wait_count.setVisibility(View.GONE);
                txt_wait.setText("周围暂无车辆，请稍候再试...");
                break;
            case 2:
                if (drivingRouteOverlay != null) {
                    drivingRouteOverlay.removeFromMap();
                }
                if (mStartPosition == null) {
                    mStartPosition = new LatLng(Double.valueOf(zpOrderModel.getDeplatitude().toString()), Double.valueOf(zpOrderModel.getDeplongitude().toString()));
                }
                if (mEndPosition == null) {
                    mEndPosition = new LatLng(Double.valueOf(zpOrderModel.getDestlatitude().toString()), Double.valueOf(zpOrderModel.getDestlongitude().toString()));
                }
                ly_wait.setVisibility(View.VISIBLE);
                sp.orderid().put(zpOrderModel.getId());
                bindData();
                if (!sp.driverLat().get().equals("")) {
                    driverLat = sp.driverLat().get();
                }
                if (!sp.driverLon().get().equals("")) {
                    driverLon = sp.driverLon().get();
                }
                if ((driverLat != null && !driverLat.equals("")) && (driverLon != null && !driverLon.equals(""))) {
                    mDriverPosition = new LatLng(Double.parseDouble(driverLat), Double.parseDouble(driverLon));
                    flag = 1;//模拟去接客
                    span = 500;
                    searchRouteResult(RouteSearch.DRIVING_SINGLE_DEFAULT);//模拟司机位置前来接驾绘制路线
                }
                handler.postDelayed(driverRunnable, 35000);

                break;
            case 3:
                actionbar_title.setText("司机已到达");
                txt_wait_show.setVisibility(View.VISIBLE);
                txt_wait_show.setText("司机已达到您的上车地，请准备上车");
                if (mStartPosition == null) {
                    mStartPosition = new LatLng(Double.valueOf(zpOrderModel.getDeplatitude().toString()), Double.valueOf(zpOrderModel.getDeplongitude().toString()));
                }
                if (mEndPosition == null) {
                    mEndPosition = new LatLng(Double.valueOf(zpOrderModel.getDestlatitude().toString()), Double.valueOf(zpOrderModel.getDestlongitude().toString()));
                }
                handler.removeCallbacks(driverRunnable);
                getDriverPosition();

                bindData();
//                getJiJiaGuiZe();
                break;
            case 4:
                actionbar_title.setText("开始服务");
                txt_wait_show.setText("行程开始，请您系好安全带。");

                if (mStartPosition == null) {
                    mStartPosition = new LatLng(Double.valueOf(zpOrderModel.getDeplatitude().toString()), Double.valueOf(zpOrderModel.getDeplongitude().toString()));
                }
                if (mEndPosition == null) {
                    mEndPosition = new LatLng(Double.valueOf(zpOrderModel.getDestlatitude().toString()), Double.valueOf(zpOrderModel.getDestlongitude().toString()));
                }
                bindData();
                line1.setVisibility(View.GONE);
                re_cancel_trip.setVisibility(View.GONE);
                if (mCarLocationMark != null) {
                    mCarLocationMark.remove();
                }
                if (drivingRouteOverlay != null) {
                    drivingRouteOverlay.removeFromMap();
                }
                if (smoothMarker != null && smoothMarker.getMarker() != null) {
                    smoothMarker.getMarker().remove();
                }
                flag = 2;//模拟接到客
//                if (zpOrderModel.getIscallsomeone().equals("0")) {
//                    getLatLonList();
//                    //设置定位监听
//                    aMap.setLocationSource(this);
//                    //是否可触发定位并显示定位层
//                    aMap.setMyLocationEnabled(true);
//                    //定位的小图标 默认是蓝点 其实就是一张图片
//                    myLocationStyle = new MyLocationStyle();
//                    myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.car_icon));
//                    myLocationStyle.radiusFillColor(android.R.color.transparent);
//                    myLocationStyle.strokeColor(android.R.color.transparent);
//                    myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);
//                    aMap.setMyLocationStyle(myLocationStyle);
//                    mLocationTask.setOnLocationGetListener(this);
//                    mLocationTask.startLocate(7);
//                } else if (zpOrderModel.getIscallsomeone().equals("1")) {
//                    handler.postDelayed(runnable, 40000);
//                }

                getJiJiaGuiZe();
                handler.postDelayed(runnable, 40000);

                break;
            case 5:
                actionbar_title.setText("行程结束");
                ly_wait.setVisibility(View.GONE);
                if (mStartPosition == null) {
                    mStartPosition = new LatLng(Double.valueOf(zpOrderModel.getDeplatitude().toString()), Double.valueOf(zpOrderModel.getDeplongitude().toString()));
                }
                if (mEndPosition == null) {
                    mEndPosition = new LatLng(Double.valueOf(zpOrderModel.getDestlatitude().toString()), Double.valueOf(zpOrderModel.getDestlongitude().toString()));
                }
                sp.orderid().put("0");
                sp.driverLat().put("");
                sp.driverLon().put("");
                bindData();
                line1.setVisibility(View.GONE);
                re_cancel_trip.setVisibility(View.GONE);
                //到达目的地
                if (mCarLocationMark != null) {
                    mCarLocationMark.remove();
                }
                if (myLocationStyle != null) {
                    myLocationStyle.showMyLocation(false);
                    aMap.setMyLocationStyle(myLocationStyle);
                }
                mLocationTask.stopLocate();
                handler.removeCallbacks(runnable);
                mOverlayList.add(mTraceoverlay);
                lat = "";
                lon = "";
//                getLatLonList();
                getJiJiaGuiZe();
                zoomToSpan(450);
//                locationList = parseTraceLocationListNew(dbUtils.getLocationList(zpOrderModel.getId()));
//                LBSTraceClient mTraceClient = new LBSTraceClient(getApplicationContext());
//                mTraceClient.queryProcessedTrace(2, locationList, LBSTraceClient.TYPE_AMAP, this);
                break;
            case 6:
                actionbar_title.setText("行程结束");
                if (mStartPosition == null) {
                    mStartPosition = new LatLng(Double.valueOf(zpOrderModel.getDeplatitude().toString()), Double.valueOf(zpOrderModel.getDeplongitude().toString()));
                }
                if (mEndPosition == null) {
                    mEndPosition = new LatLng(Double.valueOf(zpOrderModel.getDestlatitude().toString()), Double.valueOf(zpOrderModel.getDestlongitude().toString()));
                }

                bindData();
                line1.setVisibility(View.GONE);
                re_cancel_trip.setVisibility(View.GONE);
                ly_zhifu.setVisibility(View.VISIBLE);
                txt_money.setText(zpOrderModel.getFactprice().subtract(zpOrderModel.getFarupprice()).toString());
                voucherid = zpOrderModel.getInvoicestatus();
                if (zpOrderModel.getFarupprice().compareTo(new BigDecimal(0.00)) == 0) {
                    re_youhui.setVisibility(View.GONE);
                } else {
                    String youhui = String.format("%.2f", Float.parseFloat(zpOrderModel.getFarupprice().toString()));
                    re_youhui.setVisibility(View.VISIBLE);
                    txt_youhui.setText(youhui);
                }

                //TODO： 暂时注销
                if (myLocationStyle != null) {
                    myLocationStyle.showMyLocation(false);
                    aMap.setMyLocationStyle(myLocationStyle);
                }
                if (mLocationTask != null) {
                    mLocationTask.stopLocate();
                }
                zoomToSpan(450);
                break;
            case 7:

                break;
            case -1:
                sp.orderid().put("0");
                YuYin yuYin = new YuYin(this);
                yuYin.yuyinbobao("订单已被平台取消");
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            MsgModel msg = (MsgModel) intent.getExtras().get("msgModel");
            if (intent.getExtras().getString("extraStr") != null && !intent.getExtras().getSerializable("extraStr").equals("")) {
                String[] strs = intent.getExtras().getString("extraStr").split(",");
                driverLon = strs[0];
                driverLat = strs[1];
            }
            zpOrderModel = msg.getFdata();
            putshType = msg.getType();
            YuYin yuYin = new YuYin(this);

            switch (msg.getType()) {
                case 1:
                    TastyToast.makeText(this, msg.getMessage(), app.LONG, app.WARNING);
                    timeCode.onFinish();
                    if (mStartPosition == null) {
                        mStartPosition = new LatLng(Double.valueOf(zpOrderModel.getDeplatitude().toString()), Double.valueOf(zpOrderModel.getDeplongitude().toString()));
                    }
                    if (mEndPosition == null) {
                        mEndPosition = new LatLng(Double.valueOf(zpOrderModel.getDestlatitude().toString()), Double.valueOf(zpOrderModel.getDestlongitude().toString()));
                    }
                    txt_wait_count.setVisibility(View.GONE);
                    txt_wait.setText("周围暂无车辆，请稍候再试...");
                    break;
                case 2:
                    ly_wait.setVisibility(View.VISIBLE);
                    yuYin.yuyinbobao("等待接驾");
                    if (drivingRouteOverlay != null) {
                        drivingRouteOverlay.removeFromMap();
                    }
                    if (mStartPosition == null) {
                        mStartPosition = new LatLng(Double.valueOf(zpOrderModel.getDeplatitude().toString()), Double.valueOf(zpOrderModel.getDeplongitude().toString()));
                    }
                    if (mEndPosition == null) {
                        mEndPosition = new LatLng(Double.valueOf(zpOrderModel.getDestlatitude().toString()), Double.valueOf(zpOrderModel.getDestlongitude().toString()));
                    }
                    sp.orderid().put(zpOrderModel.getId());
                    sp.driverLat().put(driverLat);
                    sp.driverLon().put(driverLon);
                    bindData();
                    mDriverPosition = new LatLng(Double.parseDouble(driverLat), Double.parseDouble(driverLon));
//        removeMarkers();
                    flag = 1;//模拟去接客
                    span = 500;
                    searchRouteResult(RouteSearch.DRIVING_SINGLE_DEFAULT);//模拟司机位置前来接驾绘制路线
                    handler.postDelayed(driverRunnable, 35000);

                    break;
                case 3:
                    actionbar_title.setText("司机已到达");
                    txt_wait_show.setText("司机已达到您的上车地，请准备上车");
                    yuYin.yuyinbobao("司机已到达");
                    if (mStartPosition == null) {
                        mStartPosition = new LatLng(Double.valueOf(zpOrderModel.getDeplatitude().toString()), Double.valueOf(zpOrderModel.getDeplongitude().toString()));
                    }
                    if (mEndPosition == null) {
                        mEndPosition = new LatLng(Double.valueOf(zpOrderModel.getDestlatitude().toString()), Double.valueOf(zpOrderModel.getDestlongitude().toString()));
                    }
                    handler.removeCallbacks(driverRunnable);
                    getDriverPosition();
                    bindData();
                    break;
                case 4:
                    actionbar_title.setText("开始服务");
                    txt_wait_show.setText("行程开始，请您系好安全带");
                    yuYin.yuyinbobao("开始服务");
//                    if (mCarLocationMark != null) {
//                        mCarLocationMark.remove();
//                    }
                    if (mStartPosition == null) {
                        mStartPosition = new LatLng(Double.valueOf(zpOrderModel.getDeplatitude().toString()), Double.valueOf(zpOrderModel.getDeplongitude().toString()));
                    }
                    if (mEndPosition == null) {
                        mEndPosition = new LatLng(Double.valueOf(zpOrderModel.getDestlatitude().toString()), Double.valueOf(zpOrderModel.getDestlongitude().toString()));
                    }

                    bindData();
                    line1.setVisibility(View.GONE);
                    re_cancel_trip.setVisibility(View.GONE);
                    if (drivingRouteOverlay != null) {
                        drivingRouteOverlay.removeFromMap();
                    }
                    if (smoothMarker.getMarker() != null) {
                        smoothMarker.getMarker().remove();
                    }
                    flag = 2;//模拟接到客
                    //TODO: 判断是否自己乘车还是替他人叫车
//                    if (zpOrderModel.getIscallsomeone().equals("0")) {
//                        handler.postDelayed(runnable,40000);
//                        //设置定位监听
//                        aMap.setLocationSource(this);
//                        //是否可触发定位并显示定位层
//                        aMap.setMyLocationEnabled(true);
//                        //定位的小图标 默认是蓝点 其实就是一张图片
//                        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.car_icon));
//                        myLocationStyle.radiusFillColor(android.R.color.transparent);
//                        myLocationStyle.strokeColor(android.R.color.transparent);
//                        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);
//                        aMap.setMyLocationStyle(myLocationStyle);
//                        mLocationTask.setOnLocationGetListener(this);
//                        mLocationTask.startLocate(7);
//                    } else if (zpOrderModel.getIscallsomeone().equals("1")) {
//                        handler.postDelayed(runnable, 40000);
//                    }
                    getJiJiaGuiZe();
                    handler.postDelayed(runnable, 40000);


                    break;
                case 5:
                    actionbar_title.setText("行程结束");
                    yuYin.yuyinbobao("行程结束");
                    ly_wait.setVisibility(View.GONE);
                    if (mStartPosition == null) {
                        mStartPosition = new LatLng(Double.valueOf(zpOrderModel.getDeplatitude().toString()), Double.valueOf(zpOrderModel.getDeplongitude().toString()));
                    }
                    if (mEndPosition == null) {
                        mEndPosition = new LatLng(Double.valueOf(zpOrderModel.getDestlatitude().toString()), Double.valueOf(zpOrderModel.getDestlongitude().toString()));
                    }
                    sp.orderid().put("0");
                    sp.driverLat().put("");
                    sp.driverLon().put("");
                    bindData();

                    if (mCarLocationMark != null) {
                        mCarLocationMark.remove();
                    }
                    myLocationStyle.showMyLocation(false);
                    aMap.setMyLocationStyle(myLocationStyle);
                    handler.removeCallbacks(runnable);
                    mLocationTask.stopLocate();
                    mOverlayList.add(mTraceoverlay);
                    lat = "";
                    lon = "";
                    getLatLonList();
//                    LBSTraceClient mTraceClient = new LBSTraceClient(getApplicationContext());
//                    mTraceClient.queryProcessedTrace(2, locationList, LBSTraceClient.TYPE_AMAP, this);
                    zoomToSpan(450);
                    break;
                case 6:
                    actionbar_title.setText("行程结束");
                    ly_yugu.setVisibility(View.GONE);
                    if (mStartPosition == null) {
                        mStartPosition = new LatLng(Double.valueOf(zpOrderModel.getDeplatitude().toString()), Double.valueOf(zpOrderModel.getDeplongitude().toString()));
                    }
                    if (mEndPosition == null) {
                        mEndPosition = new LatLng(Double.valueOf(zpOrderModel.getDestlatitude().toString()), Double.valueOf(zpOrderModel.getDestlongitude().toString()));
                    }

                    bindData();
                    ly_zhifu.setVisibility(View.VISIBLE);
                    String price = zpOrderModel.getFactprice().subtract(zpOrderModel.getFarupprice()).toString();
                    txt_money.setText(String.format("%.2f", Float.parseFloat(price)));
                    if (zpOrderModel.getFarupprice().compareTo(new BigDecimal(0.00)) == 0) {
                        re_youhui.setVisibility(View.GONE);
                    } else {
                        String youhui = String.format("%.2f", Float.parseFloat(zpOrderModel.getFarupprice().toString()));
                        re_youhui.setVisibility(View.VISIBLE);
                        txt_youhui.setText(youhui);
                    }
                    //TODO： 暂时注销
                    if (myLocationStyle != null) {
                        myLocationStyle.showMyLocation(false);
                        aMap.setMyLocationStyle(myLocationStyle);
                    }
                    mLocationTask.stopLocate();
                    zoomToSpan(450);
                    break;
                case 7:

                    break;
                case -1:
                    sp.orderid().put("0");
                    yuYin.yuyinbobao("订单已被平台取消");
                    finish();
                    break;
                default:
                    break;
            }
        }
    }


    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            getLatLonList();
            //要做的事情，这里再次调用此Runnable对象，以实现每两秒实现一次的定时器操作
            handler.postDelayed(runnable, 40000);

        }
    };

    Runnable driverRunnable = new Runnable() {
        @Override
        public void run() {
            getDriverPosition();
            handler.postDelayed(driverRunnable, 35000);
        }
    };

    @Background
    void getDriverPosition() {
        ResultModel<DriverPositionModel> res = izpOrderFinder.getDriverPosition(zpOrderModel.getId());
        showDriverPositionResult(res);
    }

    @UiThread
    void showDriverPositionResult(ResultModel<DriverPositionModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    driverPositionModel = res.getData();
                    mDriverPosition = new LatLng(Double.parseDouble(driverPositionModel.getLatitude().toString()), Double.parseDouble(driverPositionModel.getLongitude().toString()));
                    if (drivingRouteOverlay != null) {
                        drivingRouteOverlay.removeFromMap();
                    }
                    if (putshType == 2) {
//                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(carLatlng));
                        searchRouteResult(RouteSearch.DRIVING_SINGLE_DEFAULT);//模拟司机位置前来接驾绘制路线
                    } else if (putshType == 3) {
                        MarkerOptions markerOptions = new MarkerOptions();
                        if (mCarLocationMark == null) {
                            markerOptions.icon(BitmapDescriptorFactory
                                    .fromResource(R.mipmap.car_icon))
                                    .position(mDriverPosition);
                        } else {
                            mCarLocationMark.remove();
                            markerOptions.icon(BitmapDescriptorFactory
                                    .fromResource(R.mipmap.car_icon));
                            markerOptions.position(mDriverPosition);
                        }

                        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
                        aMap.moveCamera(CameraUpdateFactory.changeLatLng(mDriverPosition));
                        mCarLocationMark = aMap.addMarker(markerOptions);
                    }

                }
            } else {
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
            }
        }
    }

    @Background
    void getLatLonList() {
        ResultModel<LatLonListModel> res = izpOrderFinder.getLonLatList(zpOrderModel.getId(), lat, lon);
        showLatLonResult(res);
    }

    @UiThread
    void showLatLonResult(ResultModel<LatLonListModel> res) {
        if (res != null) {
            ly_yugu.setVisibility(View.VISIBLE);

            //乘客上车时间
            Date departDate = zpOrderModel.getDeptime();
            String departtime = getcueDate(departDate);
            //当前时间
            Date currentDate = new Date();
            //计算时间差
            long diff = currentDate.getTime() - departDate.getTime();
            long minutes = diff / (1000 * 60);
            txt_time.setText(minutes + "分钟");
            int depart = Integer.parseInt(departtime);

            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    LatLonListModel latLonModels = res.getData();
                    BigDecimal distanceDriver = latLonModels.getDrivermile();
                    calculationAmount(depart, minutes, distanceDriver);
                    if (latLonModels.getIspoint() != null && !latLonModels.getIspoint().equals("")
                            && latLonModels.getIspoint().equals("1")) {
                        if (latLonModels.getPoints() != null) {
                            locationList.clear();
                            locationList = parseTraceLocationList(latLonModels.getPoints());
                            if (locationList.size() > 0) {
                                if (putshType == 4) {
                                    MarkerOptions markerOptions = new MarkerOptions();
                                    LatLng carLatLng = new LatLng(locationList.get(locationList.size() - 1).getLatitude(),
                                            locationList.get(locationList.size() - 1).getLongitude());
                                    if (mCarLocationMark == null) {
                                        markerOptions.icon(BitmapDescriptorFactory
                                                .fromResource(R.mipmap.car_icon))
                                                .position(carLatLng);
                                    } else {
                                        mCarLocationMark.remove();
                                        markerOptions.icon(BitmapDescriptorFactory
                                                .fromResource(R.mipmap.car_icon));
                                        markerOptions.position(carLatLng);
                                    }
                                    mCarLocationMark = aMap.addMarker(markerOptions);
                                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(carLatLng));
//                                    lat = String.valueOf(locationList.get(locationList.size() - 1).getLatitude());
//                                    lon = String.valueOf(locationList.get(locationList.size() - 1).getLongitude());
                                    if (latLonModels.getIsjiupian() != null && !latLonModels.getIsjiupian().equals("") &&
                                            latLonModels.getIsjiupian().equals("1")) {
                                        driverLatLonList.clear();
                                        for (int i = 0; i < locationList.size(); i++) {
                                            driverLatLonList.add(new LatLng(locationList.get(i).getLatitude(), locationList.get(i).getLongitude()));
                                        }
                                        if (mpolyline != null) {
                                            mpolyline.setPoints(driverLatLonList);
                                        } else {
                                            mpolyline = aMap.addPolyline(mPolyoptions);
                                            mpolyline.setPoints(driverLatLonList);
                                        }

//                                    mTraceoverlay.add(driverLatLonList);
//                                    int dis = mTraceoverlay.getDistance();
//                                    mTraceoverlay.setDistance(mTraceoverlay.getDistance() + distanceDriver.intValue());
                                    }


                                } else if (putshType == 5) {
                                    if (latLonModels.getIsjiupian() != null && !latLonModels.getIsjiupian().equals("") &&
                                            latLonModels.getIsjiupian().equals("1")) {
                                        driverLatLonList.clear();
                                        for (int i = 0; i < locationList.size(); i++) {
                                            driverLatLonList.add(new LatLng(locationList.get(i).getLatitude(), locationList.get(i).getLongitude()));
                                        }
                                        if (mpolyline != null) {
                                            mpolyline.remove();
                                        }
                                        if (driverLatLonList != null && driverLatLonList.size() > 0) {
                                            aMap.addPolyline(new PolylineOptions()
                                                    .color(Color.GRAY)
                                                    .width(25).addAll(driverLatLonList));
                                        }
                                    }
                                }
                            }
                        }
                    }


                }
            } else {
                Logger.d(res.getErrmsg());
//                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
            }
        }
    }


    public static List<TraceLocation> parseTraceLocationList(
            List<LatLonModel> list) {
        List<TraceLocation> traceList = new ArrayList<TraceLocation>();
        if (list == null) {
            return traceList;
        }
        for (int i = 0; i < list.size(); i++) {
            TraceLocation location = new TraceLocation();
            LatLonModel amapLocation = list.get(i);
            location.setBearing(amapLocation.getBearing());
            location.setLatitude(amapLocation.getLatitue());
            location.setLongitude(amapLocation.getLongitude());
            location.setSpeed(amapLocation.getSpeed());
            location.setTime(amapLocation.getTime());
            traceList.add(location);
        }
        return traceList;
    }

    private void bindData() {
        re_wait.setVisibility(View.GONE);
        txt_drivername.setText(zpOrderModel.getDrivername());
        txt_vehicleno.setText(zpOrderModel.getVehicleno());
        txt_vehiclecolor.setText(zpOrderModel.getVehiclecolor());
        txt_carmodel.setText(zpOrderModel.getCarmodel());
        if (zpOrderModel.getAvatar() != null && !zpOrderModel.getAvatar().equals("")) {
            Uri uri = Uri.parse(zpOrderModel.getAvatar() + RequestUrl.avatar);
            img_avatar.setImageURI(uri);
        }
        ly_trip.setVisibility(View.VISIBLE);
    }


    private void initpolyline() {
        mPolyoptions = new PolylineOptions();
        mPolyoptions.width(40);
        mPolyoptions.setCustomTexture(BitmapDescriptorFactory.fromResource(R.mipmap.grasp_trace_line));

    }

    @Override
    public void onMapLoaded() {
        addStartLocationMark();
        addEndLocationMark();
    }

    private void addStartLocationMark() {
        MarkerOptions markerOptions = new MarkerOptions();
        if (mStartLocationMark == null) {
            markerOptions.icon(BitmapDescriptorFactory
                    .fromResource(R.mipmap.up))
                    .position(mStartPosition);
        } else {
            mStartLocationMark.remove();
            markerOptions.icon(BitmapDescriptorFactory
                    .fromResource(R.mipmap.up));
            markerOptions.position(mStartPosition);

        }
        mStartLocationMark = aMap.addMarker(markerOptions);
        markers.add(mStartLocationMark);

    }

    private void addEndLocationMark() {
        MarkerOptions markerOptions = new MarkerOptions();
        if (mEndLocationMark == null) {
            markerOptions.icon(BitmapDescriptorFactory
                    .fromResource(R.mipmap.down))
                    .position(mEndPosition);
        } else {
            mEndLocationMark.remove();
            markerOptions.icon(BitmapDescriptorFactory
                    .fromResource(R.mipmap.down));
            markerOptions.position(mEndPosition);

        }
        mEndLocationMark = aMap.addMarker(markerOptions);
        markers.add(mEndLocationMark);
    }

    //根据屏幕的位置对路线进行适应屏幕的缩放
    private void zoomToSpan(int span) {
        List<LatLng> latLngs = new ArrayList<LatLng>();
        latLngs.add(mStartPosition);
        latLngs.add(mEndPosition);
        LatLngBounds.Builder b = LatLngBounds.builder();
        for (LatLng latLng : latLngs) {
            b.include(latLng);
        }
        LatLngBounds bounds = b.build();
//        aMap.animateCamera(CameraUpdateFactory.newLatLngBoundsRect(bounds, 100, 100, 350, 350));
        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, span));
    }

    @Click
    void txt_cancel_order() {
        if (zpOrderModel != null) {
            if (zpOrderModel.getId() != null && !zpOrderModel.getId().equals("")) {
                progress.show("正在取消订单");
                RCancelZPOrderModel cancelModel = new RCancelZPOrderModel();
                cancelModel.setOrderid(zpOrderModel.getId());
                cancelModel.setType("1");
                cancelZPOrder(cancelModel);
            }
        }


    }

    /**
     * 开始搜索路径规划方案
     */
    public void searchRouteResult(int mode) {
        if (mStartPosition == null) {
            TastyToast.makeText(this, "定位中，稍后再试...", app.SHORT, app.WARNING);
            return;
        }
        if (mEndPosition == null) {
            TastyToast.makeText(this, "终点未设置", app.SHORT, app.WARNING);
        }
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo();
        if (flag == 1) {
            fromAndTo = new RouteSearch.FromAndTo(
                    new LatLonPoint(mDriverPosition.latitude, mDriverPosition.longitude),
                    new LatLonPoint(mStartPosition.latitude, mStartPosition.longitude));
        } else if (flag == 2) {
            fromAndTo = new RouteSearch.FromAndTo(
                    new LatLonPoint(mStartPosition.latitude, mStartPosition.longitude),
                    new LatLonPoint(mEndPosition.latitude, mEndPosition.longitude));
        }
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, mode, null,
                null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
        mRouteSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询

    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int errorCode) {
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (driveRouteResult != null && driveRouteResult.getPaths() != null) {
                if (driveRouteResult.getPaths().size() > 0) {

                    MarkerOptions markerOptions = new MarkerOptions();
                    if (mCarLocationMark == null) {
                        markerOptions.icon(BitmapDescriptorFactory
                                .fromResource(R.mipmap.car_icon))
                                .position(mDriverPosition);
                    } else {
                        mCarLocationMark.remove();
                        markerOptions.icon(BitmapDescriptorFactory
                                .fromResource(R.mipmap.car_icon));
                        markerOptions.position(mDriverPosition);
                    }
                    mCarLocationMark = aMap.addMarker(markerOptions);

                    mDriveRouteResult = driveRouteResult;
                    final DrivePath drivePath = mDriveRouteResult.getPaths()
                            .get(0);
                    duration = (int) drivePath.getDuration();
                    int distance = (int) ((drivePath.getDistance() / 250) * 1.5 + 1);
                    Logger.d("distance :" + distance);
                    Logger.d(duration);
                    drivingRouteOverlay = new DrivingRouteOverlay(
                            this, aMap, drivePath,
                            mDriveRouteResult.getStartPos(),
                            mDriveRouteResult.getTargetPos(), null);
                    drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                    drivingRouteOverlay.setIsColorfulline(false);//是否用颜色展示交通拥堵情况，默认true
                    drivingRouteOverlay.removeFromMap();
                    drivingRouteOverlay.addToMap(flag);
                    drivingRouteOverlay.zoomToSpan(span);
//                    move(mDriverPosition);
//                    if (flag == 1) {
//                        latLngs = drivingRouteOverlay.mLatLngsOfPath;
//                        move();
//                    }
                    Logger.d("路线第一个点坐标: " + latLngs.get(0).latitude + "   " + latLngs.get(0).longitude);
                } else if (driveRouteResult != null && driveRouteResult.getPaths() == null) {
                    TastyToast.makeText(this, "没有搜索到相关数据", app.SHORT, app.ERROR);
                }

            } else {
                TastyToast.makeText(this, "没有搜索到相关数据", app.SHORT, app.ERROR);
            }
        } else {
            TastyToast.makeText(this, String.valueOf(errorCode), app.SHORT, app.ERROR);
        }
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }

    private void move(LatLng latLng) {
        smoothMarker = new SmoothMoveMarker(aMap);
        // 设置滑动的图标
        smoothMarker.setDescriptor(BitmapDescriptorFactory.fromResource(R.mipmap.car_icon));
//        smoothMarker.setPoints(latLngs);//设置平滑移动的轨迹list
        smoothMarker.setPosition(latLng);
        smoothMarker.setTotalDuration(45000);//设置平滑移动的总时间
        smoothMarker.startSmoothMove();
        smoothMarker.setMoveListener(new SmoothMoveMarker.MoveListener() {
            @Override
            public void move(double v) {
                if (v == 0) {
                    smoothMarker.getMarker().setVisible(false);
                }
            }
        });

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mListener = null;
    }


    @Override
    public void onLocationGet(PositionEntity entity, AMapLocation aMapLocation) {
        String address = entity.getAddress().replace(entity.getProvince(), "").replace(entity.getCity(), "").replace(entity.getDistrict(), "");
        Logger.d(address);
        mStartPosition = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
//        TastyToast.makeText(this, "caozuo", app.SHORT, app.DEFAULT);
        //TODO 这个地方还需要再做修改
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(mStartPosition));
        mListener.onLocationChanged(aMapLocation);

        LocLocationModel locLocationModel = new LocLocationModel();
        locLocationModel.setOrderid(zpOrderModel.getId());
        locLocationModel.setLatitue(aMapLocation.getLatitude());
        locLocationModel.setLongitude(aMapLocation.getLongitude());
        locLocationModel.setSpeed(aMapLocation.getSpeed());
        locLocationModel.setTime(aMapLocation.getTime());
        locLocationModel.setBearing(aMapLocation.getBearing());

//        dbUtils.insertLocation(locLocationModel);
//        mPolyoptions.add(mStartPosition);
//        locationList.add(Util.parseTraceLocation(aMapLocation));
        mTracelocationlist.add(Util.parseTraceLocation(aMapLocation));

        if (mTracelocationlist.size() > tracesize - 1) {
            trace();
        }
    }

    @Override
    public void onRegecodeGet(PositionEntity entity) {
        mStartPosition = new LatLng(entity.getLatitue(), entity.getLongitude());
    }

    private void trace() {
        List<TraceLocation> locationList = new ArrayList<>(mTracelocationlist);
        LBSTraceClient mTraceClient = new LBSTraceClient(getApplicationContext());
        mTraceClient.queryProcessedTrace(1, locationList, LBSTraceClient.TYPE_AMAP, this);
        TraceLocation lastlocation = mTracelocationlist.get(mTracelocationlist.size() - 1);
        mTracelocationlist.clear();
        mTracelocationlist.add(lastlocation);
    }

    private float getDistance(List<AMapLocation> list) {
        float distance = 0;
        if (list == null || list.size() == 0) {
            return distance;
        }
        for (int i = 0; i < list.size() - 1; i++) {
            AMapLocation firstpoint = list.get(i);
            AMapLocation secondpoint = list.get(i + 1);
            LatLng firstLatLng = new LatLng(firstpoint.getLatitude(),
                    firstpoint.getLongitude());
            LatLng secondLatLng = new LatLng(secondpoint.getLatitude(),
                    secondpoint.getLongitude());
            double betweenDis = AMapUtils.calculateLineDistance(firstLatLng,
                    secondLatLng);
            distance = (float) (distance + betweenDis);
        }
        return distance;
    }


    private String getcueDate(Date time) {
        SimpleDateFormat formatter = new SimpleDateFormat("HHmm");
        String date = formatter.format(time);
        return date;
    }

    @Override
    public void onRequestFailed(int i, String s) {
//        TastyToast.makeText(this,"纠偏失败",app.SHORT,app.ERROR);
        mOverlayList.add(mTraceoverlay);
        mTraceoverlay = new TraceOverlay(aMap);
    }

    @Override
    public void onTraceProcessing(int i, int i1, List<LatLng> list) {

    }

    @Override
    public void onFinished(int lineID, List<LatLng> linepoints, int distance, int waitingtime) {
        if (lineID == 1) {
            if (linepoints != null && linepoints.size() > 0) {

                if (mpolyline != null) {
                    mpolyline.setPoints(linepoints);
                } else {
                    mpolyline = aMap.addPolyline(mPolyoptions);
                    mpolyline.setPoints(linepoints);
                }

                mTraceoverlay.add(linepoints);
                mDistance += distance;
                mTraceoverlay.setDistance(mTraceoverlay.getDistance() + distance);

//                if (mlocMarker == null) {
//                    mlocMarker = aMap.addMarker(new MarkerOptions().position(linepoints.get(linepoints.size() - 1))
//                            .icon(BitmapDescriptorFactory
//                                    .fromResource(R.mipmap.point))
//                            .title("距离：" + mDistance + "米"));
//                    mlocMarker.showInfoWindow();
//                } else {
//                    mlocMarker.setTitle("距离：" + mDistance + "米");
//                    Toast.makeText(this, "距离" + mDistance, Toast.LENGTH_SHORT).show();
//                    mlocMarker.setPosition(linepoints.get(linepoints.size() - 1));
//                    mlocMarker.showInfoWindow();
//                }
            }
        } else if (lineID == 2) {
            mpolyline.remove();
            if (linepoints != null && linepoints.size() > 0) {
                aMap.addPolyline(new PolylineOptions()
                        .color(Color.GRAY)
                        .width(25).addAll(linepoints));
            }
        }

    }

    private void calculationAmount(int depart, long minutes, BigDecimal mDistance) {


        int moringOn = Integer.parseInt(ruleModel.getMorningpeaktimeon());//早高峰开始时间
        int moringoff = Integer.parseInt(ruleModel.getMorningpeaktimeoff());//早高峰结束时间
        int eveningon = Integer.parseInt(ruleModel.getEveningpeaktimeon());//晚高峰结束时间
        int eveningoff = Integer.parseInt(ruleModel.getMorningpeaktimeoff());//晚高峰结束开始时间
        int nighton = Integer.parseInt(ruleModel.getNighttimeon());//夜间高峰结束时间
        int nightoff = Integer.parseInt(ruleModel.getNighttimeoff());//夜间高峰结束开始时间


        BigDecimal unitpricepermile = ruleModel.getUnitpricepermile(); //每公里1.5
        BigDecimal unitpriceperminute = ruleModel.getUnitpriceperminute();//每分钟0.3元
        BigDecimal peakunitprice = ruleModel.getPeakunitprice(); //早晚高峰期加价0.3
        BigDecimal nightunitprice = ruleModel.getNightunitprice();//夜间加价0.2
        BigDecimal minconsumption = ruleModel.getMinconsumption();//最低金额8元(小于8元按8元算)

        BigDecimal price = new BigDecimal(0);
        BigDecimal gaofengzhi = new BigDecimal(0);
        BigDecimal nightgaofengzhi = new BigDecimal(0);
        if ((depart > moringOn && depart < moringoff) || (depart > eveningon && depart < eveningoff)) {
            gaofengzhi = peakunitprice;
        } else {
            gaofengzhi = new BigDecimal(0);
        }
        if (depart > nighton && depart < nightoff) {
            nightgaofengzhi = nightunitprice;

        } else {
            nightgaofengzhi = new BigDecimal(0);
        }

        BigDecimal jiajia = gaofengzhi.add(nightgaofengzhi).add(new BigDecimal(1));
        BigDecimal juli = unitpricepermile.multiply(mDistance);
        BigDecimal fenzhong = unitpriceperminute.multiply(new BigDecimal(minutes));
        price = jiajia.multiply(juli.add(fenzhong));
        if (price.compareTo(minconsumption) == -1) {
            price = minconsumption;
        }
        txt_distance.setText(mDistance + "公里");
        txt_amount.setText(price.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "元");
//        TastyToast.makeText(context, "分钟差： " + minutes + "  ,金额：" + price.toString(), app.SHORT, app.DEFAULT);

    }


    // 倒计时实现类
    class TimeCode extends CountDownTimer {

        public TimeCode(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            txt_wait_count.setText("120秒");
        }

        @Override
        public void onTick(long arg0) {
            txt_wait_count.setText(arg0 / 1000 + "秒");
        }
    }

    @Click
    void re_cancel_trip() {
        new MaterialDialog.Builder(this)
                .title("提示")
                .titleGravity(GravityEnum.CENTER)
                .titleColorRes(R.color.colorFontGray)
                .content("确定取消行程。")
                .contentColorRes(R.color.colorFontGray)
                .positiveText("确定")
                .positiveColor(ContextCompat.getColor(this, R.color.colorFontBlue))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        progress.show("正在取消订单...");
                        RCancelZPOrderModel cancelModel = new RCancelZPOrderModel();
                        cancelModel.setOrderid(zpOrderModel.getId());
                        cancelModel.setType("1");
                        cancelZPOrder(cancelModel);
                    }
                })
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(context, R.color.colorFontGray))
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                    }
                })
                .buttonsGravity(GravityEnum.CENTER)
                .show();

    }

    @Background
    void cancelZPOrder(RCancelZPOrderModel cancelModel) {
        ResultModel<String> res = izpOrderFinder.cancelZPOrder(cancelModel);
        showCancelResult(res);
    }

    @UiThread
    void showCancelResult(ResultModel<String> res) {
        progress.dismiss();
        sp.orderid().put("0");
        if (res != null) {
            if (res.getErrno().equals("0")) {
                TastyToast.makeText(this, "取消订单成功", app.SHORT, app.SUCCESS);
            } else {
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.SUCCESS);
            }
        }
        finish();
    }

    @Background
    void getJiJiaGuiZe() {
        ResultModel<ValuationRuleModel> res = izpOrderFinder.getFare(zpOrderModel.getFacetype());
        showJiJiaGuiZeResult(res);
    }

    @UiThread
    void showJiJiaGuiZeResult(ResultModel<ValuationRuleModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    ruleModel = res.getData();
                    getLatLonList();
                }
            } else {
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.SUCCESS);
            }
        }
    }

    @Background
    void getAbout() {
        ResultModel<AboutModel> res = baseFinder.getAbout();
        showResult(res);
    }

    @UiThread
    void showResult(ResultModel<AboutModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    AboutModel aboutModel = res.getData();
                    hotline = aboutModel.getFtel();
                    showDailogTel(hotline);
                }
            }
        }
    }

    @Click
    void txt_tel() {
        if (zpOrderModel.getDriverphone() != null && !zpOrderModel.getDriverphone().equals("")) {
            hotline = zpOrderModel.getDriverphone();
            showDailogTel(hotline);
        }
    }

    @Click
    void re_hotline() {
        getAbout();
    }

    private void showDailogTel(String phone) {
        new MaterialDialog.Builder(context)
                .title("提示")
                .titleGravity(GravityEnum.CENTER)
                .titleColorRes(R.color.colorFontBigGray)
                .content("您确定要拨打" + " " + phone)
                .contentColorRes(R.color.colorFontBigGray)
                .positiveText("确定")
                .positiveColor(ContextCompat.getColor(context, R.color.colorFontBlue))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        AndPermission.with(context)
                                .requestCode(100)
                                .permission(Manifest.permission.CALL_PHONE)
                                .callback(listener)
                                .rationale(new RationaleListener() {
                                    @Override
                                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                                        AndPermission.rationaleDialog(context, rationale).
                                                show();
                                    }
                                })
                                .start();
                    }
                })
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(context, R.color.colorFontGray))
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .buttonsGravity(GravityEnum.CENTER)
                .show();
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == 100) {
                //打电话
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + hotline));
                context.startActivity(intent);
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            if (requestCode == 100) {
                TastyToast.makeText(context, "获取电话权限失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR);
            }
        }
    };

    @Click
    void btn_pay() {
        progress.show("正在支付...");
        if (rb_zhifubao.isChecked()) {
            chanel = 1;
            initCharge();
        } else if (rb_weixin.isChecked()) {
            chanel = 2;
            initCharge();
        } else if (rb_yu_e.isChecked()) {
            balanceTrading.setOrderid(zpOrderModel.getId());
            balanceTrading.setType("1");
            balanceTrading.setDriverid(zpOrderModel.getDriverid());
            balanceTrading.setVoucherid(voucherid);
            getUserBalance();
//            TastyToast.makeText(this, "您选择了余额支付", app.SHORT, app.WARNING);
        } else {
            TastyToast.makeText(this, "请选择支付方式", app.SHORT, app.WARNING);
        }
    }

    private void initCharge() {
        btn_pay.setEnabled(false);
        chargeModel.setAmount(new BigDecimal(txt_money.getText().toString().trim()).toString());
        chargeModel.setType("3");
        chargeModel.setChannel(chanel);
        chargeModel.setClientIp(clinetIp);
        chargeModel.setOrderNo(zpOrderModel.getOrderid());
        chargeModel.setOrderid(zpOrderModel.getId());
        chargeModel.setVoucherid(voucherid);
        getCharge();
    }

    @Background
    void getCharge() {
        ResultModel<String> res = bankFinder.getCharge(chargeModel);
        showChargeResult(res);
    }

    @UiThread
    void showChargeResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null && !res.getData().equals("")) {
                    String data = res.getData();
                    Pingpp.createPayment(this, data);
                }
            } else {
                btn_pay.setEnabled(true);
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
                if (progress != null) {
                    progress.dismiss();
                }
            }
        }
    }

    /**
     * onActivityResult 获得支付结果，如果支付成功，服务器会收到ping++ 服务器发送的异步通知。
     * 最终支付成功根据异步通知为准
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (progress != null) {
            progress.dismiss();
        }
        btn_pay.setEnabled(true);
        //支付页面返回处理
        if (requestCode == Pingpp.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");
                if (result != null && !result.equals("")) {
                     /* 处理返回值
                 * "success" - payment succeed
                 * "fail"    - payment failed
                 * "cancel"  - user canceld
                 * "invalid" - payment plugin not installed
                 */
                    if (result.equals("success")) {
                        TastyToast.makeText(this, "支付成功", app.SHORT, app.SUCCESS);
                        RESULT_CODE = 1;
                        //TODO 专车评价车主
                        ly_pingjia.setVisibility(View.VISIBLE);
                        ly_trip.setVisibility(View.GONE);
                        ly_zhifu.setVisibility(View.GONE);


                    } else if (result.equals("fail")) {
                        RESULT_CODE = -1;
                        TastyToast.makeText(this, "支付失败", app.SHORT, app.ERROR);
                    } else if (result.equals("cancel")) {
                        RESULT_CODE = 2;
                        TastyToast.makeText(this, "您已取消支付", app.SHORT, app.WARNING);
                    } else if (result.equals("invalid")) {
                        RESULT_CODE = 3;
                        TastyToast.makeText(this, "末能安装应用", app.SHORT, app.WARNING);
                    }

                } else {
                    String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
                    String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
                    TastyToast.makeText(this, errorMsg + extraMsg, app.SHORT, app.ERROR);
                }

            }
        }
    }


    @Background
    public void getUserBalance() {
        ResultModel<UserBalance> res = bankFinder.getUserBalance();
        showBalanceResult(res);
    }

    @UiThread
    void showBalanceResult(ResultModel<UserBalance> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    UserBalance balance = res.getData();
                    if (balance.getUseramount().compareTo(new BigDecimal(0)) == 1) {
                        balanceTrading(balanceTrading);
                    } else {
                        TastyToast.makeText(this, "当前余额为0,不能进行余额支付。", app.SHORT, app.ERROR);
                        if (progress != null) {
                            progress.dismiss();
                        }
                    }
                }
            }
        }
    }

    @Background
    void balanceTrading(RBalanceTrading balanceTrading) {
        ResultModel<String> res = bankFinder.balanceTrading(balanceTrading);
        showTradingResult(res);
    }

    @UiThread
    void showTradingResult(ResultModel<String> res) {
        if (progress != null) {
            progress.dismiss();
        }
        if (res != null) {
            if (res.getErrno().equals("0")) {
                TastyToast.makeText(this, "余额支付成功", app.SHORT, app.SUCCESS);
                RESULT_CODE = 1;
                ly_pingjia.setVisibility(View.VISIBLE);
                ly_trip.setVisibility(View.GONE);
                ly_zhifu.setVisibility(View.GONE);
//                Intent intent = new Intent();
//                intent.putExtra("resultCode", RESULT_CODE);
//                setResult(5, intent);
//                this.finish();
            } else {
                RESULT_CODE = -1;
                TastyToast.makeText(this, "余额支付失败", app.SHORT, app.ERROR);
            }
        }
    }

    @Click
    void btn_cancel() {
        ly_pingjia.setVisibility(View.GONE);
        this.finish();
    }

    @Click
    void btn_confrim() {
        RZCOrderRatedModel zcOrderRatedModel = new RZCOrderRatedModel();
        zcOrderRatedModel.setId(zpOrderModel.getId());
        zcOrderRatedModel.setFlag("2");
        float rb = ratingBar.getRating();
        int rate = (int) rb;
        zcOrderRatedModel.setRate(String.valueOf(rate));
        goRated(zcOrderRatedModel);
    }

    @Background
    void goRated(RZCOrderRatedModel zcOrderRatedModel) {
        ResultModel<String> resultModel = izpOrderFinder.goZCOrderRate(zcOrderRatedModel);
        showRateResult(resultModel);
    }

    @UiThread
    void showRateResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                TastyToast.makeText(this, "评价信息提交成功", app.SHORT, app.SUCCESS);
                this.finish();
            } else {
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);

            }
        }
    }

    @Click
    void re_youhui() {
        getCanUseList(zpOrderModel.getFactprice());
    }

    @Background
    void getCanUseList(BigDecimal factprice) {
        ResultModel<List<CanUseVouchersModel>> res = vouchersFinder.getCanUse(factprice);
        showCanUseResult(res);
    }

    @UiThread
    void showCanUseResult(ResultModel<List<CanUseVouchersModel>> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    vouchersModelList = res.getData();
                    if (vouchersModelList.size() > 0) {
                        pickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                            @Override
                            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                                String youhui = String.format("%.2f", Float.parseFloat(vouchersModelList.get(options1).getAmount().toString()));
                                String price = zpOrderModel.getFactprice().subtract(vouchersModelList.get(options1).getAmount()).toString();
                                txt_money.setText(String.format("%.2f", Float.parseFloat(price)));
                                txt_youhui.setText(youhui);
                                voucherid = vouchersModelList.get(options1).getId();
                            }
                        }).setContentTextSize(12).setLineSpacingMultiplier(2).build();
                        pickerView.setPicker(vouchersModelList);
                        pickerView.show();
                    }
                }
            }
        }
    }


    /**
     * 获取外网IP地址
     */
    @Background
    void GetNetIp() {
        URL infoUrl = null;
        InputStream inStream = null;
        String line = "";
        try {
            infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
                StringBuilder strber = new StringBuilder();
                while ((line = reader.readLine()) != null)
                    strber.append(line + "\n");
                inStream.close();
                // 从反馈的结果中提取出IP地址
                int start = strber.indexOf("{");
                int end = strber.indexOf("}");
                String json = strber.substring(start, end + 1);
                if (json != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        line = jsonObject.optString("cip");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                showResult(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<TraceLocation> parseTraceLocationListNew(
            List<LocLocationModel> list) {
        List<TraceLocation> traceList = new ArrayList<TraceLocation>();
        if (list == null) {
            return traceList;
        }
        for (int i = 0; i < list.size(); i++) {
            TraceLocation location = new TraceLocation();
            LocLocationModel entity = list.get(i);
            location.setBearing(entity.getBearing());
            location.setLatitude(entity.getLatitue());
            location.setLongitude(entity.getLongitude());
            location.setSpeed(entity.getSpeed());
            location.setTime(entity.getTime());
            traceList.add(location);
        }
        return traceList;
    }


    @UiThread
    void showResult(String line) {
        clinetIp = line;
    }


    @Click
    void back_icon() {
        this.finish();
    }

    /**
     * 移除marker
     */
    public static void removeMarkers() {
        for (Marker marker : markers) {
            marker.remove();
            marker.destroy();
        }
        markers.clear();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        removeMarkers();
        mLocationTask.onDestroy();
        mMapView.onDestroy();
        handler.removeCallbacks(driverRunnable);
        handler.removeCallbacks(runnable);
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }
}
